//
//  MessageDetailViewController.m
//  zhongjianProject
//
//  Created by Farben on 2020/4/16.
//  Copyright © 2020 Farben. All rights reserved.
//

#import "MessageDetailViewController.h"
#import <WebKit/WebKit.h>
@interface MessageDetailViewController ()<WKUIDelegate,WKNavigationDelegate>
@property (nonatomic) WKWebView *webView;
@property (nonatomic) UIProgressView *progressView;
@end

@implementation MessageDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
    self.navigationController.navigationBar.translucent = NO;
    
}
#pragma mark - Getter
- (UIProgressView *)progressView {
    if (!_progressView){
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0 , kScreen_WIDTH, 2)];
        _progressView.tintColor = [UIColor redColor];
        _progressView.trackTintColor = [UIColor clearColor];
    }
    return _progressView;
}
- (WKWebView *)webView{
    if (_webView == nil) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        _webView = [[WKWebView alloc] init];
       _webView.frame = self.view.bounds;
       //创建网页配置对象
       _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
       // UI代理
       _webView.UIDelegate = self;
       // 导航代理
       _webView.navigationDelegate = self;
       // 是否允许手势左滑返回上一级, 类似导航控制的左滑返回
       _webView.allowsBackForwardNavigationGestures = YES;
       NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];
       [_webView loadRequest:request];
       //添加监测网页加载进度的观察者
       [_webView addObserver:self
                          forKeyPath:@"estimatedProgress"
                             options:0
                             context:nil];
    }
    return _webView;

}
   //kvo 监听进度 必须实现此方法
-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                      context:(void *)context{
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]
        && object == _webView) {
       NSLog(@"网页加载进度 = %f",_webView.estimatedProgress);
        self.progressView.progress = _webView.estimatedProgress;
        if (_webView.estimatedProgress >= 1.0f) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.progress = 0;
            });
        }
    }else{
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}
- (void)dealloc{
   
    //移除观察者
    [_webView removeObserver:self
                  forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
}
@end
